package com.cszy.yydqbfq.ui.activity

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.airbnb.lottie.LottieDrawable
import com.hbcysd.qybfq.R
import com.hbcysd.qybfq.databinding.ActivityMusicListBinding

import com.cszy.yydqbfq.adapter.IndexListAdapter
import com.cszy.yydqbfq.base.BaseVMActivity
import com.cszy.yydqbfq.bean.Song
import com.cszy.yydqbfq.common.PlaylistRepository

import com.cszy.yydqbfq.dialog.BottomPopupWithGeDanRecycler
import com.cszy.yydqbfq.ext.toast
import com.cszy.yydqbfq.utils.SpUtils
import com.cszy.yydqbfq.viewmodel.IndexViewModel
import com.hlyj.http.ad.NewGroMoreFeedAdManager
import com.hlyj.http.base.tool.lib_hlyj_base.bean.music.MusicListBean
import com.hlyj.http.base.tool.lib_hlyj_base.utils.BaseAppConstans

import com.hnyyac.ad.mds.IAdView
import com.hnyyac.ad.mds.IAdViewListener
import com.hnyyac.ad.mds.manager.AdManager
import com.hnyyac.ad.mds.manager.AdManager.AdLoadListener
import com.hnyyac.ad.mds.utils.BaseAdConstants
import com.kwad.sdk.core.b.a.it
import com.lzx.starrysky.manager.PlaybackStage
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class MusicListActivity : BaseVMActivity<IndexViewModel, ActivityMusicListBinding>(),IAdViewListener {
     private var category:String?=null
     private var listAdapter: IndexListAdapter? = null
    private var newGromoreFeedAd : NewGroMoreFeedAdManager? =null
    var type_proces: String? = null //功能入口类型
    override fun initView(savedInstanceState: Bundle?) {
        mViewModel.init(this)

    }

    override fun initData() {
        type_proces="第一次插屏"
        AdManager.loadChapin_nocache(
            this,
            21,
            this,
            object : AdLoadListener {
                override fun onAdLoadFailed(ad: IAdView?) {
                    newGromoreFeedAd = NewGroMoreFeedAdManager(this@MusicListActivity, BaseAdConstants.FEEDAD_Id, mBinding?.frameLayoutBanner,22)
                    newGromoreFeedAd?.loadAd()
                }
            })


        category = intent?.extras?.getString("category")
        if (category=="金曲榜"){
            mViewModel.queryMusic()
        }else if (category=="本地音乐"){
            //showLoading("正在加载音频列表...")
            mBinding.lottieView.visibility=View.VISIBLE
            mBinding.lottieView.repeatCount = LottieDrawable.INFINITE // 无限循环
            mBinding.lottieView.playAnimation()
            loadAudioList()
        }else{
            mViewModel.queryMusicByCategory(category.toString())
        }
        when (category) {
            "金曲榜" -> {
                mBinding.headTitle.headCenterTitle.text="金曲榜单"
            }
            "流行" -> {
                mBinding.headTitle.headCenterTitle.text="流行音乐"
            }
            "怀旧" -> {
                mBinding.headTitle.headCenterTitle.text="怀旧歌曲"
            }
            "摇滚" -> {
                mBinding.headTitle.headCenterTitle.text="摇滚歌曲"
            }
            "民谣" -> {
                mBinding.headTitle.headCenterTitle.text="民谣歌曲"
            }
            "说唱" -> {
                mBinding.headTitle.headCenterTitle.text="说唱歌曲"
            }
            "国风" -> {
                mBinding.headTitle.headCenterTitle.text="国风音乐"
            }
            "本地音乐" -> {
                mBinding.headTitle.headCenterTitle.text="本地音乐"
            }
        }

        mBinding.headTitle.headRightImg.setImageResource(R.mipmap.ic_import)
        mBinding.headTitle.headRightImg.imageTintList = resources.getColorStateList(R.color.black)
        mBinding.headTitle.headRightImg.visibility = if (category == "本地音乐") View.VISIBLE else View.GONE

        listAdapter= IndexListAdapter()
        mBinding.recyMusicList.layoutManager= LinearLayoutManager(this)
        mBinding.recyMusicList.adapter=listAdapter
    }

    override fun initListener() {
        //返回
        mBinding.headTitle.headBack.setOnClickListener {
           finish()
       }
        listAdapter?.setOnItemClickListener { adapter, view, position ->
            // 传递整个列表和当前点击位置
            var songList=mViewModel.convertToSongInfoList(adapter.items)
            val intent = Intent(this, PlayDetailActivity::class.java).apply {
                putParcelableArrayListExtra("MUSIC_LIST", ArrayList(songList))
                putExtra("CURRENT_POSITION", position)
            }
            startActivity(intent)
        }

        // 需要传递控件 id加入歌单点击事件
        listAdapter?.addOnItemChildClickListener(R.id.tv_add_gedanlist) { adapter, view, position ->
            // toast("点了添加歌单")
            var song_item=adapter.items.get(position)
            // 将 MusicListBean 转换为 Song
            val song = Song().apply {
                title = song_item.name ?: ""
                artist = song_item.author ?: ""
                cover = song_item.imageUrl ?: ""
                uri=song_item.songUrl
                duration = 0
                songlistbean_id = 0
            }
            val repository = PlaylistRepository()
            var geDanList = repository.getAllPlaylists()
                .filter { it.name != "本地音乐" }  // 过滤条件
            BottomPopupWithGeDanRecycler(this, geDanList,song).show(mBinding.root)
        }

        mBinding.headTitle.headRightImg.setOnClickListener {
            loadAudioList()
        }

    }

    override fun initObserve() {
        //获取音频数据
        mViewModel.queryMusicResult.observe(this){musiclist->
          listAdapter?.submitList(musiclist as List<MusicListBean>?)

        }
    }

    override fun onBackPressed() {
        super.onBackPressed()
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out) // 平滑过渡
    }
    private fun loadAudioList() {
        // 1. 立即显示加载框（UI线程）
     //   showLoading("正在加载音频列表...")

        lifecycleScope.launch {
            try {
                // 2. 在IO线程执行数据库操作
                val audioList = withContext(Dispatchers.IO) {
                    delay(500)
                    mViewModel.getAudioInfoListSync()
                }

                // 3. 回到主线程更新UI
                withContext(Dispatchers.Main) {
                    val songInfoList = mViewModel.convertToMusicListBeanList(audioList)
                    listAdapter?.submitList(songInfoList)
                    mBinding.lottieView.cancelAnimation()
                    mBinding.lottieView.visibility=View.INVISIBLE
                    toast("加载完成")
                }

            } catch (e: Exception) {
                toast("加载失败: ${e.message ?: "未知错误"}")
                dismissLoading()
            } finally {
                // 4. 确保在主线程关闭加载框
                withContext(Dispatchers.Main) {
                   // dismissLoading()
                }
            }
        }
    }
    private fun loadAudioList_onlyloacl() {
        // 1. 立即显示加载框（UI线程）
        showLoading("正在加载音频列表...")

        lifecycleScope.launch {
            try {
                // 2. 在IO线程执行数据库操作
                val audioList = withContext(Dispatchers.IO) {
                    val list = mViewModel.getAudioInfoListSync_onlylocal()
                    Log.d("AudioLoad", "从数据库获取到 ${list.size} 条记录")
                    list
                }

                // 3. 回到主线程更新UI
                withContext(Dispatchers.Main) {
                    val songInfoList = mViewModel.convertToMusicListBeanList(audioList)
                    Log.d("AudioLoad", "转换后得到 ${songInfoList.size} 条记录")
                    listAdapter?.submitList(songInfoList)
                    listAdapter?.notifyDataSetChanged()
                }

            } catch (e: Exception) {
                toast("加载失败: ${e.message ?: "未知错误"}")
            } finally {
                // 4. 确保在主线程关闭加载框
                withContext(Dispatchers.Main) {
                    dismissLoading()
                }
            }
        }
    }

    override fun onTrigger(adView: IAdView) {

    }

    override fun onAdShow(adView: IAdView) {

    }

    override fun onAdClick(adView: IAdView) {

    }

    override fun onAdClose(adView: IAdView) {
       when(type_proces){
           "第一次插屏"->{
               newGromoreFeedAd = NewGroMoreFeedAdManager(this, BaseAdConstants.FEEDAD_Id, mBinding?.frameLayoutBanner,22)
               newGromoreFeedAd?.loadAd()
           }
       }
    }

    override fun onError(msg: String) {

    }

    override fun onLoadError(adView: IAdView) {

    }

    override fun onSuccess(adView: IAdView) {

    }

    override fun onLoad(adView: IAdView) {

    }

    override fun onSkipped() {

    }

    override fun onNoAd() {

    }

    override fun onTimeOut() {

    }

}